import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, Form, FormProps, Input, Space } from 'antd';

import Upload from '@/components/upload';

import { store } from '@/store';

import { proInspectionRecordHandle } from '@/services/bizApi/shengchanxunjianjilujiekou';
import { Icon } from '@iconify/react/dist/iconify.js';

import { BizObject } from '.';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        pointRecordId: args?.rowData?.pointRecordId,
        abnormalHandleFile: values.abnormalHandleFile?.replace(/\?/g, ',')
      };

      await proInspectionRecordHandle(query);

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success('异常处理提交成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        // 编辑回填数据
        if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
          // 回填数据
          form.setFieldsValue({
            ...arg.rowData,
            abnormalHandleFile: arg.rowData.abnormalHandleFile?.replace(/,/g, '?')
          });
        } else {
          form.resetFields();
        }
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');
      return;
    }
    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增',
          edit: '异常处理',
          detail: '异常处理详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                确定
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="处理结果"
          name="abnormalHandleResult"
          rules={[
            {
              required: true,
              message: '请输入异常处理结果'
            }
          ]}
        >
          <Input.TextArea autoSize={{ minRows: 4, maxRows: 6 }} maxLength={800} />
        </Form.Item>

        <Form.Item
          label="上传附件"
          name="abnormalHandleFile"
          rules={[
            {
              required: false,
              message: '请上传附件'
            }
          ]}
        >
          <Upload listType="picture-card" accept="image/*" disabled={args?.type === 'detail'}>
            <Icon icon="ri:upload-2-fill" />
            上传图片
          </Upload>
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
